package com.bruce.util;

import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Created by bruce on 2018-11-03
 */
public class DateUtils {

    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * date 转 时间字符串,格式: yyyy-MM-dd HH:mm:ss
     */
    public static String toString(Date date) {
        if (date == null) {
            return null;
        }
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        return dtf.format(localDateTime);
    }

    //日期格式化
    public static LocalDateTime parseDate(String time) {
        return LocalDateTime.parse(time, dtf);
    }

    /**
     * 字符串时间yyyy-MM-dd HH:mm:ss 转 date
     */
    public static Date toDate(String time) {
        return Date.from(Instant.from(LocalDateTime.parse(time, dtf).atZone(ZoneId.systemDefault())));
    }

    /**
     * 判断时间 endDate - startDate 是否在指定的天数内 <br/>
     * 时间格式: yyyy-MM-dd HH:mm:ss
     */
    public static boolean inInterval(String startDate, String endDate, int intervalDays) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)){
            return false;
        }
        long ss = intervalDays * 60 * 60 * 24; //s
        long s = (toDate(endDate).getTime() / 1000 - toDate(startDate).getTime() / 1000);
        return s > 0 && s <= ss;
    }

    public static boolean notInInterval(String startDate, String endDate, int intervalDays) {
        return !inInterval(startDate, endDate, intervalDays);
    }


}
